package com.zggk.lzz.sjsb;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Switch;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.zggk.lzz.R;
import com.zggk.lzz.api.MyApplication;
import com.zggk.lzz.mvp.MVPBaseActivity;
import com.zggk.lzz.roadh.RoadSetBean;
import com.zggk.lzz.util.NoScroolGridView;
import com.zggk.lzz.util.Utils;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.lxj.matisse.Matisse;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */

public class SjsbActivity extends MVPBaseActivity<SjsbContract.View, SjsbPresenter> implements SjsbContract.View {

    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.cancle_button)
    TextView cancleButton;
    @Bind(R.id.lxbm_et)
    TextView lxbmEt;
    @Bind(R.id.lxbm_lay)
    LinearLayout lxbmLay;
    @Bind(R.id.zhwz_et)
    EditText zhwzEt;
    @Bind(R.id.sjlx_et)
    TextView sjlxEt;
    @Bind(R.id.sjlx_lay)
    LinearLayout sjlxLay;
    @Bind(R.id.sjzt_te)
    TextView sjztTe;
    @Bind(R.id.sjzt_lay)
    LinearLayout sjztLay;
    @Bind(R.id.sfsb_sw)
    Switch sfsbSw;
    @Bind(R.id.xjlz_lay)
    LinearLayout xjlzLay;
    @Bind(R.id.xlz_lay)
    LinearLayout xlzLay;
    @Bind(R.id.zlz_lay)
    LinearLayout zlzLay;
    @Bind(R.id.czfs_et)
    EditText czfsEt;
    @Bind(R.id.save_te)
    TextView saveTe;
    @Bind(R.id.activity_disease_new_scrollview)
    ScrollView activityDiseaseNewScrollview;
    @Bind(R.id.disease_new_parent_layout)
    RelativeLayout diseaseNewParentLayout;
    @Bind(R.id.add_pic_grid)
    NoScroolGridView addPicGrid;
    @Bind(R.id.add_pic_lay)
    LinearLayout addPicLay;
    @Bind(R.id.sb_v)
    View sbV;
    @Bind(R.id.x_rb)
    RadioButton xRb;
    @Bind(R.id.xlz_rb)
    RadioButton xlzRb;
    @Bind(R.id.zlc_rb)
    RadioButton zlcRb;
    @Bind(R.id.yy_img)
    ImageView yyImg;
    @Bind(R.id.yy2_img)
    ImageView yy2Img;
    private OptionsPickerView pickerView;
    private int childViewPosition;//点击拍照获取的childveiw下标
    private SjsbAddGird sjsbAddGird;
    private Map<Integer, SjsbAddGird> mapAdapter = new HashMap<>();
    private List<LxBean.DataBean.RecordsBean> lxData = new ArrayList<>();
    private LxBean.DataBean.RecordsBean lxInfo;
    private int REQUEST_CODE_CHOOSE = 66;
    private static String APPID = "5bf211f5";
    private String dictationResultStr;
    private List<String> xf = new ArrayList<>();
    private List<String> zong = new ArrayList<>();
    private AMapLocationClient locationClientSingle = null;
    private double longitude;
    private double latitude;

    public void setChildViewPosition(int childViewPosition) {
        this.childViewPosition = childViewPosition;
    }

    @Override
    public void onRequestError(String msg) {
        if (msg.equals("加载中...")){
            mPresenter.getData(SjsbActivity.this);
        }
    }

    @Override
    protected int getLayout() {
        return R.layout.act_sjsb;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        initView();
        xRb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                xRb.setChecked(true);
                xlzRb.setChecked(false);
                zlcRb.setChecked(false);
            }
        });
        xlzRb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                xRb.setChecked(false);
                xlzRb.setChecked(true);
                zlcRb.setChecked(false);
            }
        });
        zlcRb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                xRb.setChecked(false);
                xlzRb.setChecked(false);
                zlcRb.setChecked(true);
            }
        });
        initDw();
    }

    private void initDw() {
        locationClientSingle = new AMapLocationClient(this.getApplicationContext());
        /**
         * 单次客户端的定位监听
         */
        AMapLocationListener locationSingleListener = new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation location) {
                longitude = location.getLongitude();//经度
                latitude = location.getLatitude();//纬度
            }
        };
        locationClientSingle.setLocationListener(locationSingleListener);
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
//获取一次定位结果：
//该方法默认为false。
        mLocationOption.setOnceLocation(true);
//关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
//给定位客户端对象设置定位参数
        locationClientSingle.setLocationOption(mLocationOption);
//启动定位
        locationClientSingle.startLocation();
    }

    private void getkdxf(final EditText kdaxfdate) {
        dictationResultStr = "[";
        // 语音配置对象初始化
        SpeechUtility.createUtility(SjsbActivity.this, SpeechConstant.APPID + "=" + APPID);
        // 1.创建SpeechRecognizer对象，第2个参数：本地听写时传InitListener
        SpeechRecognizer mIat = SpeechRecognizer.createRecognizer(SjsbActivity.this, null);
        // 交互动画
        final RecognizerDialog iatDialog = new RecognizerDialog(SjsbActivity.this, null);
        // 2.设置听写参数，详见《科大讯飞MSC API手册(Android)》SpeechConstant类
        mIat.setParameter(SpeechConstant.DOMAIN, "iat");
        mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        mIat.setParameter(SpeechConstant.ACCENT, "mandarin");
        // 3.开始听写
        iatDialog.setListener(new RecognizerDialogListener() {
            @Override
            public void onResult(RecognizerResult results, boolean isLast) {

                if (!isLast) {
                    dictationResultStr += results.getResultString() + ",";
                } else {
                    dictationResultStr += results.getResultString() + "]";
                }
                if (isLast) {
                    List<DictationResult> dictationResultList = JSON.parseArray(dictationResultStr, DictationResult.class);
                    String finalResult = "";
                    for (int i = 0; i < dictationResultList.size() - 1; i++) {
                        finalResult += dictationResultList.get(i)
                                .toString();
                    }
                    xf.clear();
                    zong.clear();
                    zong.add(kdaxfdate.getText().toString());
                    zong.add(finalResult);
                    kdaxfdate.setText(listToString2(zong));
                    kdaxfdate.requestFocus();
                    kdaxfdate.setSelection(listToString2(zong).length());
                }
            }

            @Override
            public void onError(SpeechError error) {
                error.getPlainDescription(true);
            }

        });
        iatDialog.show();

    }

    public static String listToString2(List<String> list) {
        StringBuilder sb = new StringBuilder();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (i < list.size() - 1) {
                    sb.append(list.get(i));
                } else {
                    sb.append(list.get(i));
                }
            }
        }
        return sb.toString();
    }

    private void initView() {
        setTitleText("事件上报");
        goBack();
        mPresenter.getData(SjsbActivity.this);
        sfsbSw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    sbV.setVisibility(View.VISIBLE);
                    xjlzLay.setVisibility(View.VISIBLE);
                    xlzLay.setVisibility(View.VISIBLE);
                    zlzLay.setVisibility(View.VISIBLE);
                } else {
                    sbV.setVisibility(View.GONE);
                    xjlzLay.setVisibility(View.GONE);
                    xlzLay.setVisibility(View.GONE);
                    zlzLay.setVisibility(View.GONE);
                }
            }
        });
        ArrayList<Drawable> listPicture = new ArrayList<>();
        ArrayList<String> listImgUrl = new ArrayList<>();
        Drawable addPicture = getResources().getDrawable(R.drawable.img_add_pic);
        listPicture.add(addPicture);
        final int childPosition = addPicLay.getChildCount();
        sjsbAddGird = new SjsbAddGird(this, listPicture, listImgUrl, childPosition);
        addPicGrid.setAdapter(sjsbAddGird);
        mapAdapter.put(childPosition, sjsbAddGird);
        sjlxEt.setText("病害");
        sjztTe.setText("待处置");
    }

    @OnClick({R.id.yy_img, R.id.yy2_img, R.id.save_te, R.id.lxbm_lay, R.id.sjlx_lay, R.id.sjzt_lay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.yy_img:
                getkdxf(czfsEt);
                break;
            case R.id.yy2_img:
                mPresenter.getWz(lxInfo.getRoadCode(), longitude+"", latitude+"");
                break;
            case R.id.save_te:
                if (Utils.isNull(lxbmEt.getText().toString())) {
                    ToastUtils.showShort("请选择路线");
                    return;
                }
                if (Utils.isNull(zhwzEt.getText().toString())) {
                    ToastUtils.showShort("请输入桩号");
                    return;
                }
                if (Utils.isNull(sjlxEt.getText().toString())) {
                    ToastUtils.showShort("请选择事件类型");
                    return;
                }
                if (Utils.isNull(sjztTe.getText().toString())) {
                    ToastUtils.showShort("请选择事件状态");
                    return;
                }
                SjsbBean sjsbBean = new SjsbBean();
                sjsbBean.setOrgCode(MyApplication.spUtils.getString("OrgCode"));//政区编码
                sjsbBean.setOrgName(MyApplication.spUtils.getString("OrgName"));//政区名称
                sjsbBean.setRoadCode(lxInfo.getRoadCode());//路线编码
                sjsbBean.setRoadCodeAll(lxInfo.getRoadCode());//路线编码全称
                sjsbBean.setRoadName(lxInfo.getRoadName());//路线名称
                sjsbBean.setStake(zhwzEt.getText().toString());//起点桩号
                sjsbBean.setFindtime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));//发现时间
                sjsbBean.setFindadress(lxInfo.getRoadCode() + " " + lxInfo.getRoadName());//发现地点
                sjsbBean.setEtype(sjlxEt.getText().toString());//事件类型
                sjsbBean.setDoinfo(czfsEt.getText().toString());//处置方式
                sjsbBean.setState(sjztTe.getText().toString());//事件状态
                if (sfsbSw.isChecked()) {//是否上报
                    if (xRb.isChecked()) {
                        sjsbBean.setIssub("1");
                    } else if (xlzRb.isChecked()) {
                        sjsbBean.setIssub("2");
                    } else if (zlcRb.isChecked()) {
                        sjsbBean.setIssub("3");
                    }
                } else {
                    sjsbBean.setIssub("0");//不上报0，乡1，县2，总3
                }
                sjsbBean.setRemark("");
                sjsbBean.setCreateUserCode(MyApplication.spUtils.getString("UserID"));
                sjsbBean.setCreateUserName(MyApplication.spUtils.getString("UserName"));
                sjsbBean.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                String imgStr2 = "";
                ArrayList<String> listImgUrl2 = sjsbAddGird.getListImgUrl();
                if (listImgUrl2 != null && listImgUrl2.size() > 0) {
                    for (int k = 0; k < listImgUrl2.size(); k++) {
                        if (k == 0) {
                            imgStr2 += listImgUrl2.get(k);
                        } else {
                            imgStr2 += "," + listImgUrl2.get(k);
                        }
                    }
                }
                if (!StringUtils.isSpace(imgStr2)) {
                    String[] strArr = imgStr2.split(",");
                    if (strArr != null && strArr.length > 0) {
                        ArrayList<SjsbBean.PICBean> listPic = new ArrayList<>();
                        for (int i = 0; i < strArr.length; i++) {
                            SjsbBean.PICBean picInfo = new SjsbBean.PICBean();
                            String imgUrl = strArr[i];
                            String nameStr = imgUrl.substring(imgUrl.lastIndexOf("/") + 1, imgUrl.length());
                            String typeStr = imgUrl.substring(imgUrl.lastIndexOf(".") + 1, imgUrl.length());
                            picInfo.setPicFileName(nameStr);
                            picInfo.setPicFileType(typeStr);
                            String strBlob = Utils.bmpToBase64String(imgUrl);
                            picInfo.setPicDataBlob(strBlob);
                            listPic.add(picInfo);
                        }
                        sjsbBean.setPIC(listPic);
                    }
                }
                sjsbBean.setJd(longitude + "");
                sjsbBean.setWd(latitude + "");
                String sss = JSON.toJSONString(sjsbBean);
                mPresenter.addData(sss, SjsbActivity.this);
                break;
            case R.id.lxbm_lay:
                List<String> lxDatas = new ArrayList<>();
                if (lxData != null && lxData.size() > 0) {
                    for (int i = 0; i < lxData.size(); i++) {
                        lxDatas.add(lxData.get(i).getRoadName() + " " + lxData.get(i).getStartStake()
                                + "—" + lxData.get(i).getEndStake());
                    }
                }
                setOption(lxDatas, lxbmEt, 1);
                break;
            case R.id.sjlx_lay:
                List<String> sjlxDatas = new ArrayList<>();
                sjlxDatas.add("保洁");
                sjlxDatas.add("病害");
                sjlxDatas.add("应急");
                sjlxDatas.add("路政");
                sjlxDatas.add("其他");
                setOption(sjlxDatas, sjlxEt, 2);
                break;
            case R.id.sjzt_lay:
                List<String> sjztDatas = new ArrayList<>();
                sjztDatas.add("已处置");
                sjztDatas.add("待处置");
                setOption(sjztDatas, sjztTe, 3);
                break;
        }
    }

    public void setOption(final List<String> datas, final TextView textview, final int type) {
        pickerView = new OptionsPickerView.Builder(SjsbActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                if (type == 1) {
                    lxInfo = lxData.get(options1);
                }
                //返回的分别是三个级别的选中位置
                textview.setText(datas.get(options1));
            }
        }).setLayoutRes(R.layout.progress_lay, new CustomListener() {
            @Override
            public void customLayout(View v) {
                final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                TextView ivCancel = (TextView) v.findViewById(R.id.iv_cancel);
                tvSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pickerView.returnData();
                        pickerView.dismiss();
                    }
                });
                ivCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pickerView.dismiss();
                    }
                });
            }
        }).build();
        pickerView.setPicker(datas);
        pickerView.show();
    }

    @Override
    public void getDatas(LxBean.DataBean dataBean) {
        lxData.addAll(dataBean.getRecords());
    }

    @Override
    public void addDatas() {
        RoadSetBean roadSetBean = new RoadSetBean();
        roadSetBean.setUserId(MyApplication.spUtils.getString("UserID"));
        roadSetBean.setLon(String.valueOf(longitude));//经度116.2
        roadSetBean.setLat(String.valueOf(latitude));//纬度39.56
        roadSetBean.setNowTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        String sss = JSON.toJSONString(roadSetBean);
        mPresenter.setRoad2(sss);
    }

    @Override
    public void setRoad2s() {
        ToastUtils.showShort("上传成功");
        finish();
    }

    @Override
    public void getWzs(WzBean.DataBean wzBean) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            final SjsbAddGird dieaseAddGird = mapAdapter.get(childViewPosition);
            final ArrayList<Drawable> listPicture = dieaseAddGird.getListPicture();
            final ArrayList<String> listImgUrl = dieaseAddGird.getListImgUrl();
            String imgPath = Matisse.obtainCropResult(data);
            listPicture.remove(listPicture.size() - 1);
            Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
            if (bitmap != null) {
                Drawable drawable = new BitmapDrawable(bitmap);
                listPicture.add(drawable);
                listImgUrl.add(imgPath);
                Drawable addPicture = getResources().getDrawable(R.drawable.img_add_pic);
                listPicture.add(addPicture);
                dieaseAddGird.notifyDataSetChanged();
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        locationClientSingle.stopLocation();//停止定位后，本地定位服务并不会被销毁
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        locationClientSingle.onDestroy();
    }
}
